#include <iostream>

using namespace std;

class complex
{
public:
	complex (double r=0, double i=0) {
		real = r; 
		imag = i; 
	}
	
	const complex operator+(const complex& c); 
	
	void print() const {
		cout<<" (" <<real<<", "<<imag<<") "<<endl; 
	}
	
private:
	double real, imag;
};
// 运算符重载 -- 通过成员方法
const complex complex::operator+(const complex& c) {
	double r = real + c.real;
	double i = imag + c.imag;
	return complex(r, i);
}


class complex2 {
public:
	complex2 (double r=0, double i=0) {
		real=r; 
		imag=i; 
	}
	
	friend const complex2 operator+
	(const complex2& c1, const complex2& c2); //Binary
	
	void print() const { 
		cout<<" (" <<real<<", "<<imag<<") "<<endl; 
	}
	
private:
	double real, imag;
}; // 运算符重载 -- 通过友元
const complex2 operator +(const complex2& c1, const complex2& c2)
{
	double r = c1. real + c2.real;
	double i = c1. imag + c2.imag;
	return complex2(r, i);
}


int main(int argc, char *argv[]) {
	// 通过成员方法进行运算符重载 -- 注意参数的顺序
	complex c, c1(3.5, 5.5);
	c=c1+1.5; // ok: c=c1.operator +(1.5);		1.5 double -> complex(1.5, 0) 调用了构造函数
	c.print(); // (5, 5.5)
	
	//error: c=1.5+c1; 		error: c=1.5.operator +(c1);	针对前置的1.5，无法调用构造函数
	cout << "==================" << endl;
	
	// 通过友元进行运算符重载
	complex2 o1, o2(3.5, 5.5);
	o1=o2+1.5; // ok: c=operator +(c1, 1.5);		1.5 double -> complex(1.5, 0) 调用了构造函数
	o1.print(); // (5, 5.5)
	o1=1.5+o2; //ok: c=operator +(1.5, c1);		1.5 double -> complex(1.5, 0) 调用了构造函数
	o1.print(); // (5, 5.5)
}